'''
Author: caoniu caoniu@jushuitan.com
Date: 2023-06-07 19:53:09
LastEditors: caoniu caoniu@jushuitan.com
LastEditTime: 2023-06-07 20:11:07
FilePath: /undefined/Users/kongdelu/py_project/chatServer.py
Description: Post请求
'''

import platform
import subprocess
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel

from langchain.document_loaders import YoutubeLoader

import openai
import json
import uvicorn

tags_metadata = [
    {
        "name": "youtubetrans",
        "description": "传入youtube英文视频网址，自动将视频内容翻译为中文文字.",
    },
    {
        "name": "chat",
        "description": "和OpenAi的大语言模型进行聊天.",
    },
]

app = FastAPI(openapi_tags=tags_metadata)

'''
youtube视频翻译（本人亲测部署在linux系统上会报错，
这可能是由于翻译服务可能需要用到微软的服务，
如遇到错误请部署到windwos系统上）
'''


@app.get("/youtubetrans/", tags=["youtubetrans"])
async def youtubetrans(url: str):
    youtube_url_prefix = "https://www.youtube.com/watch?"
    if url.lower().startswith(youtube_url_prefix):
        loader = YoutubeLoader.from_youtube_url(url, add_video_info=True, language=[
                                                'zh-Hans'], translation='zh-Hans')
        result = loader.load()
        output = result[0].page_content
        return output
    else:
        return "请输入正确的YouTube视频网址！"


'''ai聊天'''


class ChatItem(BaseModel):
    prompt: str


@app.post("/chat/", tags=["chat"])
async def chat(item: ChatItem):
    print(item)
    model = 'gpt-3.5-turbo-0613'
    openai.api_key = "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"
    response = openai.ChatCompletion.create(
        model=model,
        messages=[
            {"role": "user", "content": item.prompt},
            {"role": "system", "content": "The following are exerpts from conversations with AI assistant,If I don't know the answer to a particular question, just says 'I don't know'"}
        ],
        functions=function_descriptions,
        function_call="auto",
    )
    ai_response_message = response["choices"][0]["message"]
    # 判断是否需要函数调用
    if ai_response_message.content is None:
        # Get function name, and its arguments
        function_name = ai_response_message['function_call']['name']
        arguments = json.loads(ai_response_message['function_call']['arguments'])
        print(function_name)
        print(arguments);
        # Locate the function and make the call
        the_function = globals().get(function_name)
        parameter_values = []
        for parameter_name in arguments:
            parameter_values.append(arguments[parameter_name])
        returned_value = the_function(*parameter_values)
        return returned_value
    else:
        # 不需要函数调用，则直接返回回答的内容
        return ai_response_message.content

function_descriptions = [
  {
      "name": "get_weather",
      "description": "Get the weather for the specified city when user ask",
      "parameters": {
          "type": "object",
          "properties": {
              "city": {
                  "type": "string",
                  "description": "The city name",
              }
          },
          "required": ["city"],
      },
      "name": "send_email",
      "description": "Send email to the target when user asked",
      "parameters": {
          "type": "object",
          "properties": {
              "source": {
                  "type": "string",
                  "description": "The source email",
              },
              "target": {
                  "type": "string",
                  "description": "The target email",
              },
              "body": {
                  "type": "string",
                  "description": "The email body",
              },

          },
          "required": ["source","target","body"],
      },
    }
]

def get_weather(city):
  return f'{city} weather is sunny'

def send_email(source,target,body):
  if source == "your_email@example.com":
    return f'Please provide your email'
  ''' Do some action '''
  return f'Already send email to {target} from {source}, and the email body is {body}'

if __name__ == "__main__":
    uvicorn.run(host="0.0.0.0", port=8001, app=app)
